package com.api.config;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.common.config.AlipayProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author Renbowen
 * @ClassName AliPayConfig
 * @Description 阿里云支付配置
 * @Date 2020/10/12 10:57
 */
@Configuration
@Slf4j
public class AliPayConfig {

    private final AlipayProperties alipayProperties;

    public AliPayConfig(AlipayProperties alipayProperties) {
        this.alipayProperties = alipayProperties;
    }

    @Bean
    public AlipayClient alipayClient() throws AlipayApiException, FileNotFoundException {

        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        //设置网关地址
        certAlipayRequest.setServerUrl(alipayProperties.getServerUrl());
        //设置应用Id
        certAlipayRequest.setAppId(alipayProperties.getAppId());
        //设置应用私钥
        certAlipayRequest.setPrivateKey(alipayProperties.getPrivateKey());
        //设置请求格式，固定值json
        certAlipayRequest.setFormat(alipayProperties.getFormat());
        //设置字符集
        certAlipayRequest.setCharset(alipayProperties.getCharset());
        //设置签名类型
        certAlipayRequest.setSignType(alipayProperties.getSignType());

        // 设置应用公钥证书路径
//        certAlipayRequest.setCertContent(getJarEnvironmentFile(alipayProperties.getCertPath()));
        certAlipayRequest.setCertPath(ResourceUtils.getURL(alipayProperties.getCertPath()).getPath());
        //设置支付宝公钥证书路径
        //certAlipayRequest.setAlipayPublicCertContent(getJarEnvironmentFile(alipayProperties.getAlipayPublicCertPath()));
        certAlipayRequest.setAlipayPublicCertPath(ResourceUtils.getURL(alipayProperties.getAlipayPublicCertPath()).getPath());
        //设置支付宝根证书路径
//        certAlipayRequest.setRootCertContent(getJarEnvironmentFile(alipayProperties.getRootCertPath()));
        certAlipayRequest.setRootCertPath(ResourceUtils.getURL(alipayProperties.getRootCertPath()).getPath());
        return new DefaultAlipayClient(certAlipayRequest);
    }


    /**
     * 解决jar部署情况下的路径找不到问题->直接获取文件内容
     * @param path 文件路径
     * @return 文件内容
     */
    public String getJarEnvironmentFile(String path){
        String data = "";
        ClassPathResource cpr = new ClassPathResource(path);
        try {
            byte[] byteData = FileCopyUtils.copyToByteArray(cpr.getInputStream());
            data = new String(byteData, StandardCharsets.UTF_8);
        } catch (IOException e) {
            log.error("文件地址获取失败：{{}}",path);
        }
        return data;
    }
}
